package redtask

import (
	redisdk "github.com/darwinOrg/go-redis"
	"github.com/hibiken/asynq"
)

var (
	asynqClient    *asynq.Client
	asynqServer    *asynq.Server
	asynqMux       *asynq.ServeMux
	redisClientOpt = &customRedisClientOpt{}
)

type customRedisClientOpt struct{}

func (*customRedisClientOpt) MakeRedisClient() any {
	return redisdk.GetUniversalClient()
}

type TaskConfig struct {
	asynq.Config
}

func InitClient() {
	checkRedisUniversalClient()
	asynqClient = asynq.NewClient(redisClientOpt)
}

func CloseClient() error {
	return asynqClient.Close()
}

func InitServer(cfg *TaskConfig) {
	checkRedisUniversalClient()
	asynqServer = asynq.NewServer(redisClientOpt, cfg.Config)
	asynqMux = asynq.NewServeMux()
}

func RunServer() error {
	return asynqServer.Run(asynqMux)
}

func checkRedisUniversalClient() {
	if redisdk.GetUniversalClient() == nil {
		panic("redis client is nil")
	}
}
